<template>
    <div class="resetPassword">
        <div class="reset-content">
            <el-steps :active="activeIndex" finish-status="success" align-center>
                <el-step title="输入账号名"></el-step>
                <el-step title="设置密码"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <el-form ref="resetForm" :model="resetForm" :rules="resetRules" v-show="activeIndex == 0">
                <el-form-item prop="account">
                    <el-input v-model="resetForm.account" placeholder="请输入您的账号（账号、手机号或邮箱）">
                        <span slot="prefix" class="iconfont icon-zhanghao"></span>
                    </el-input>
                </el-form-item>
                <el-form-item prop="graphCaptcha" class="flexItem">
                    <el-input v-model="resetForm.graphCaptcha" placeholder="请输入图形验证码">
                        <span slot="prefix" class="iconfont icon-tuxingyanzhengma"></span>
                    </el-input>
                    <img :src="graphCaptchaData.base64GraphCaptcha" @click="getGraphCaptcha" />
                </el-form-item>
                <el-form-item prop="smsCaptcha" class="flexItem">
                    <el-input v-model="resetForm.smsCaptcha" placeholder="请输入短信验证码">
                        <span slot="prefix" class="iconfont icon-yanzhengma"></span>
                    </el-input>
                    <el-button @click="sendSmsCaptcha" :disabled="isDisabled" type="primary" plain>{{buttonName}}</el-button>
                </el-form-item>
            </el-form>
            <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" v-show="activeIndex == 1">
                <el-form-item prop="password">
                    <el-input v-model="passwordForm.password" placeholder="请输入密码" type="password">
                        <span slot="prefix" class="iconfont icon-mima"></span>
                    </el-input>
                </el-form-item>
                <el-form-item prop="confirmPassword">
                    <el-input v-model="passwordForm.confirmPassword" placeholder="请确认密码" type="password">
                        <span slot="prefix" class="iconfont icon-querenmima"></span>
                    </el-input>
                </el-form-item>
            </el-form>
            <div v-show="activeIndex == 3">
                <el-result icon="success">
                    <template slot="extra">
                        <router-link to="/login">
                            <el-button type="primary">使用新密码登录</el-button>
                        </router-link>
                    </template>
                </el-result>
            </div>
            <div v-show="activeIndex != 3">
                <el-button type="primary" @click="next" style="width: 100%;margin-bottom: 20px">下一步</el-button>
                <p class="tips">
                    <router-link to="/login">返回登录</router-link>
                </p>
            </div>
        </div>
    </div>
</template>

<script>
import { getGraphCaptcha, verifyGraphCaptcha, sendSmsCaptchaToUser, verifySmsCaptchaForUser, forgetPassword } from "@/api/login";
export default {
    name: "resetPassword",
    data() {
        var validateMobile = (rule, value, callback) => {
            var reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
            if (!value) {
                callback(new Error('请输入手机号'));
            } else if (!reg.test(value)) {
                callback(new Error('请输入正确的手机号'));
            } else {
                callback();
            }
        };
        var validateGraphCaptcha = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入图形验证码'));
            } else {
                if (this.isSend) {
                    callback();
                } else {
                    var param = {
                        graphCaptcha: this.resetForm.graphCaptcha,
                        graphCaptchaId: this.graphCaptchaData.id
                    }
                    verifyGraphCaptcha(param).then(resp => {
                        if (resp.status == 0) {
                            callback();
                        } else {
                            callback(new Error(resp.message));
                        }
                    });
                }
            }
        };
        var validateSmsCaptcha = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入短信验证码'));
            } else {
                if (!this.isSend) {
                    callback(new Error('请先点击发送短信验证码'));
                } else {
                    callback();
                }
            }
        }
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.passwordForm.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            activeIndex: 0,
            resetForm: {
                account: "",
                graphCaptcha: "",
                smsCaptcha: ""
            },
            resetRules: {
                account: [{ required: true, message: '请输入您的账号（账号、手机号或邮箱）', trigger: 'blur' }],
                graphCaptcha: [{ required: true, validator: validateGraphCaptcha, trigger: 'blur' }],
                smsCaptcha: [{ required: true, validator: validateSmsCaptcha, trigger: 'blur' }],
            },
            passwordForm: {
                password: "",
                confirmPassword: ""
            },
            passwordRules: {
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
                confirmPassword: [{ required: true, validator: validatePass, trigger: 'blur' }],
            },
            graphCaptchaData: {},
            countDown: 60,//倒计时
            buttonName: "发送短信验证码",//按钮初始化文字
            isDisabled: false,//是否禁用按钮
            isSend: false,
            timeStamp: null, //重新发送时间戳
        }
    },
    methods: {
        getGraphCaptcha() {
            getGraphCaptcha().then(resp => {
                if (resp.status == 0) {
                    this.graphCaptchaData = resp.data;
                }
            });
        },
        sendSmsCaptcha() {
            if (!this.isDisabled) {
                this.isDisabled = true;
                this.$refs['resetForm'].validateField("account", mobileValid => {
                    if (!mobileValid) {
                        this.$refs['resetForm'].validateField("graphCaptcha", valid => {
                            if (!valid) {
                                this.isSend = true;
                                var param = {
                                    graphCaptcha: this.resetForm.graphCaptcha,
                                    graphCaptchaId: this.graphCaptchaData.id,
                                    account: this.resetForm.account
                                }
                                sendSmsCaptchaToUser(param).then(resp => {
                                    if (resp.status == 0) {
                                        this.timeStamp = new Date().getTime() + resp.data.leftTimeToResend;
                                        this.countDown = (resp.data.leftTimeToResend) / 1000;
                                        this.countTime();
                                    } else {
                                        this.isDisabled = this.isSend = false;
                                        this.$antMessage.warning(resp.message);
                                    }
                                });
                            } else {
                                this.isDisabled = false;
                            }
                        });
                    } else {
                        this.isDisabled = false;
                    }
                });
            }
        },
        countTime() {
            let timerId = setInterval(() => {
                this.countDown--;
                this.buttonName = this.countDown + "秒后重试";
                if (this.countDown <= 0) {
                    clearInterval(timerId);
                    this.timeStamp = null;
                    this.buttonName = "发送短信验证码";
                    this.countDown = 60;
                    this.isDisabled = false;
                }
            }, 1000);
        },
        next() {
            if (this.activeIndex == 0) {
                this.$refs['resetForm'].validate((valid) => {
                    if (valid) {
                        var param = {
                            graphCaptcha: this.resetForm.graphCaptcha,
                            account: this.resetForm.account,
                            smsCaptcha: this.resetForm.smsCaptcha
                        }
                        verifySmsCaptchaForUser(param).then(resp => {
                            if (resp.status == 0) {
                                this.activeIndex += 1;
                            } else {
                                this.$antMessage.warning(response.message);
                            }
                        });
                    }
                });
            } else if (this.activeIndex == 1) {
                this.$refs['passwordForm'].validate((valid) => {
                    if (valid) {
                        var param = {
                            account: this.resetForm.account,
                            password: this.passwordForm.password,
                            confirmPassword: this.passwordForm.confirmPassword,
                            smsCaptcha: this.resetForm.smsCaptcha,
                        }
                        forgetPassword(param).then(resp => {
                            if (resp.status == 0) {
                                this.activeIndex = 3;
                            } else {
                                this.$antMessage.warning(response.message);
                            }
                        });
                    }
                });
            }
        }
    },
    created() {
        this.getGraphCaptcha();
        window.addEventListener('beforeunload', () => {
            if (this.timeStamp) {
                localStorage.setItem("resetPassTime", this.timeStamp);
            }
        })
        this.timeStamp = localStorage.getItem("resetPassTime") || null;
        if (this.timeStamp) { //刷新页面、跳转路由倒计时继续
            let nowStamp = new Date().getTime();
            var stamp = this.timeStamp - nowStamp;
            if (stamp <= 0) {
                this.buttonName = "发送短信验证码";
                this.isDisabled = false;
            } else {
                this.isDisabled = true;
                this.countDown = parseInt(Math.abs(stamp) / 1000);
                this.countTime();
            }
            localStorage.removeItem("resetPassTime");
        }
    },
    beforeRouteLeave(to, from, next) {
        if (this.timeStamp) {
            localStorage.setItem("resetPassTime", this.timeStamp);
        }
        next();
    }
}
</script>

<style lang="scss">
.resetPassword {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-color: #f3f6ff;
    background-image: url("../../assets/images/loginBg.png");
    background-size: 100% 100%;
    .reset-content {
        width: 720px;
        background: #fff;
        padding: 40px 80px 80px;
        box-shadow: 0px 0px 30px 0px rgba(12, 8, 47, 0.15);
        border-radius: 20px;
        .el-form-item {
            margin-bottom: 30px;
            .el-input__inner {
                border-radius: 6px;
                padding-left: 38px;
            }
            .el-input__prefix {
                left: 0;
                width: 38px;
            }
            .iconfont {
                color: #b7c1c9 !important;
            }
        }
        .el-form-item__error {
            padding-top: 8px;
        }
        .flexItem .el-form-item__content {
            display: flex;
            align-items: center;
            .el-button,
            img {
                cursor: pointer;
                width: 160px;
                height: 40px;
                flex-shrink: 0;
                margin-left: 20px;
            }
            img {
                border-radius: 6px;
                border: 1px solid #6b5ee2;
            }
        }
    }
    .el-result__extra {
        margin-top: 75px;
        width: 100%;
        .el-button {
            width: 100%;
        }
    }
    .tips {
        a {
            color: #6b5ee2;
        }
    }
}
</style>